#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <ctime>
#include "blockqueue.hpp"
#include "task.hpp"

void* consumer(void* args)
{
    bq::BlockQueue<Task> *bq = static_cast<bq::BlockQueue<Task>*>(args);
    // 1. 从 bq 中拿数据
    // 2. 处理数据，处理某种业务
    while(true)
    {
        sleep(1);
        Task t;
        bq->pop(t);
        int res = t();
        std::cout << t.format() << " = " << res << std::endl;
    }
}
void* productor(void* args)
{
    bq::BlockQueue<Task> *bq = static_cast<bq::BlockQueue<Task>*>(args);
    // 1. 从某处生产数据
    // 2. 将数据放入 bq
    std::string ops = "+-*/%";
    while (true)
    {
        int x = rand() % 20 + 1;
        int y = rand() % 10 + 1;
        char op = ops[rand() % ops.size()];
        Task t(x, y, op);
        bq->push(t);
        std::cout << t.format() << " = ?" << std::endl;
    }
}
int main()
{
    srand((unsigned int)time(nullptr) ^ getpid());
    bq::BlockQueue<Task> *bq = new bq::BlockQueue<Task>();
    pthread_t c, p;
    pthread_create(&c, nullptr, consumer, (void*)bq);
    pthread_create(&p, nullptr, productor, (void*)bq);

    pthread_join(c, nullptr);
    pthread_join(p, nullptr);
    delete bq;
    return 0;
}